// Package xlogging 封装login.
package xlogging

import (
	"bytes"
	"fmt"
	"strings"

	"github.com/sirupsen/logrus"
)

const (
	FIELDLOGTAG = "_logtag_"
)

// xlog Level.

type Level = logrus.Level
type Logger = logrus.Logger

var globalDefaultLogger *Logger

type Entry = logrus.Entry

// LogFormat 日志格式化.
type LogFormat struct {
	TimestampFormat string
	PrintCaller     bool
}

func init() {
	globalDefaultLogger = logrus.New()
	Init()
}

// Init 初始化Log.
func Init() {
	initLog(globalDefaultLogger)
}

func initLog(logger *Logger) {
	// 初始化.
	formatter := &LogFormat{
		TimestampFormat: "2006-01-02 15:04:05.999",
		PrintCaller:     true,
	}

	logger.SetFormatter(formatter)
	logger.SetReportCaller(true)

}

func (l *LogFormat) Format(entry *logrus.Entry) ([]byte, error) {

	var b *bytes.Buffer
	if entry.Buffer != nil {
		b = entry.Buffer
	} else {
		b = &bytes.Buffer{}
	}
	b.WriteString(entry.Time.Format(l.TimestampFormat))
	if tag, ok := entry.Data[FIELDLOGTAG]; ok {
		b.WriteByte('[')
		b.WriteString(tag.(string))
		b.WriteByte(']')
	}
	b.WriteByte('[')
	b.WriteString(strings.ToUpper(entry.Level.String()))
	b.WriteByte(']')
	if entry.Message != "" {
		b.WriteString(entry.Message)
	}
	// 文件名以及行数.
	if l.PrintCaller {
		b.WriteString(fmt.Sprintf("[%s:%d]", entry.Caller.File, entry.Caller.Line))
	}
	b.WriteByte('\n')
	return b.Bytes(), nil
}

// Tag 对外提供.
func Tag(tag string) *Entry {
	return globalDefaultLogger.WithFields(logrus.Fields{FIELDLOGTAG: tag})
}
